for i, v in enumerate(nums): # 判断当前值是否和上一位值是否重复,重复的就跳过,目的是为了去除重复解 if i > 0and nums[i] == nums[i - 1]: continue
for k in range(i + 1, size): if k > i + 1and nums[k] == nums[k - 1]: continue
left = k + 1 right = size - 1
# 只要左指针没有超过右指针,那么就一直循环 while left < right: sum_value = v + nums[left] + nums[right] + nums[k] if sum_value > target: # 和值大于 target, 右指针需要左移 right -= 1 elif sum_value < target: # 和值小于 target, 左指针需要右移 left += 1 else: result.append([v, nums[left], nums[right], nums[k]]) # 判断左边界和右边界是否和下一位值重复,目的是为了去除重复解 while left != right and nums[left] == nums[left + 1]: left += 1 while left != right and nums[right] == nums[right - 1]: right -= 1 # 最后左右指针各移动一步 right -= 1 left += 1 return result
funcfourSum(nums []int, target int) [][]int { var result [][]int
iflen(nums) < 4{ return result }
size := len(nums) sort.Ints(nums)
for i, v:= range nums{ if i > 0 && nums[i] == nums[i-1]{ continue }
for k := i + 1; k < size; k++ { if k > i+1 && nums[k] == nums[k-1] { continue }
left := k +1 right := size - 1
for left < right{ sumValue := v + nums[left] + nums[right] + nums[k] if sumValue > target{ right -=1 }elseif sumValue < target { left += 1 }else{ result = append(result, []int{v, nums[left], nums[right], nums[k]})
for left != right && nums[left] == nums[left+1]{ left += 1 } for left != right && nums[right] == nums[right-1]{ right -=1 } left +=1 right -=1 } } } } return result }